package cn.tedu.bonfire.front.content.word;

import cn.hutool.core.io.resource.ClassPathResource;
import cn.hutool.core.io.resource.Resource;
import com.github.houbb.sensitive.word.api.IWordDeny;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.charset.StandardCharsets;
import java.nio.file.*;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

// 自定义敏感词
// 注意每一行为一个敏感词，单行不能只包括空格，否则，也会把空格识别为敏感词
@Slf4j
public class MyWordDeny implements IWordDeny {
    @Override
    public List<String> deny() {
        List<String> list = new ArrayList<>();

        try {
            Resource mySensitiveWords = new ClassPathResource("mySensitiveWords.txt");
            URI uri = mySensitiveWords.getUrl().toURI();
            Path mySensitivePath;
            FileSystem fileSystem = null;

            try {
                if (uri.getScheme().equals("jar")) {
                    fileSystem = FileSystems.newFileSystem(uri, Collections.emptyMap());
                    mySensitivePath = fileSystem.getPath("mySensitiveWords.txt");
                } else {
                    mySensitivePath = Paths.get(uri);
                }
                list = Files.readAllLines(mySensitivePath, StandardCharsets.UTF_8);

            } catch (FileSystemAlreadyExistsException e) {
                fileSystem = FileSystems.getFileSystem(uri);
                mySensitivePath = fileSystem.getPath("mySensitiveWords.txt");
                list = Files.readAllLines(mySensitivePath, StandardCharsets.UTF_8);

            } catch (IOException e) {
                // 处理异常
            } finally {
                if (fileSystem != null) {
                    fileSystem.close();
                }
            }

        } catch (URISyntaxException | IOException ioException) {
            log.error("读取非敏感词文件错误！" + ioException.getMessage());
        }

        return list;
    }
}
